package in.iqing.module.data;

import android.content.Context;
import android.os.Handler;
import android.util.LruCache;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import in.iqing.control.api.ApiHelper;
import in.iqing.control.api.callback.ParagraphCallback;
import in.iqing.control.helper.LogHelper;
import in.iqing.model.bean.Chapter;
import in.iqing.model.bean.Paragraph;
import in.iqing.module.data.task.ClearCacheTask;

/**
 * Created by neavo on 2015/5/15.
 */

public class DataHelper {
    private static final String TAG = "DataHelper";
    private Handler handler;
    private ExecutorService service;
    private static DataHelper singleton;
    private static final int ONE_MB = 1024 * 1024 * 1024;

    // chapter id, chapter paragraph
    private LruCache<Integer, List<Paragraph>> paragraphCache;

    private DataHelper() {
        this.handler = new Handler();
        this.service = Executors.newFixedThreadPool(1);
        paragraphCache = new LruCache<>(ONE_MB);
    }

    public static synchronized DataHelper getSingleton() {
        if (singleton == null) {
            singleton = new DataHelper();
        }

        return singleton;
    }

    public synchronized void clearCache(Context ctx, ClearCacheTask.ICallback callback) {
        service.execute(new ClearCacheTask(handler, ctx, callback));
    }

    public synchronized void getParagraphs(Chapter chapter, GetQingParagraphCallback callback) {
        callback.onStart();
        List<Paragraph> paragraphs = paragraphCache.get(chapter.getId());
        if (paragraphs == null) {
            LogHelper.warn(TAG, "read paragraph from server");
            // TODO cancel request when cancel load page
            ApiHelper.getSingleton().getParagraph(chapter.getContentUrl(), chapter.getContentUrl(), new LoadQingParagraphCallback(callback, chapter));
        } else {
            LogHelper.warn(TAG, "read paragraph from cache");
            callback.onFinish(paragraphs);
        }
    }

    private class LoadQingParagraphCallback extends ParagraphCallback {
        GetQingParagraphCallback callback;
        Chapter chapter;

        public LoadQingParagraphCallback(GetQingParagraphCallback callback, Chapter chapter) {
            this.callback = callback;
            this.chapter = chapter;
        }

        @Override
        public void onSuccess(List<Paragraph> bookList) {
            if (bookList != null) {
                paragraphCache.put(chapter.getId(), bookList);
            }
            if (callback != null) {
                callback.onFinish(bookList);
            }
        }

        @Override
        public void onFailure(int code, String msg) {
            if (callback != null) {
                callback.onFinish(EMPTY);
            }
        }
    }

    public interface GetQingParagraphCallback {

        void onStart();

        void onFinish(List<Paragraph> paragraphs);
    }
}
